/*
 * Copyright (c) 2018, dreamkaylee@foxmail.com All Rights Reserved.
 */

package com.limk.jconfig.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Constants;
import com.common.exception.ParameterException;
import com.common.manager.ClientManager;
import com.common.shiro.util.ShiroCacheUtil;
import com.common.util.IpUtil;
import com.common.util.StringUtil;
import com.common.web.BaseController;

/**
 * 认证控制器
 * @author limk
 * @date 2018年2月13日 上午9:21:11
 * @version 1.0
 */
@Controller
@RequestMapping("/")
public class LoginController extends BaseController {
    
    /**
     * 首页
     * @return
     */
	@GetMapping(value = "/")
    public String index() {
        return "redirect:/index";
    }

    /**
     * 首页
     * @param model
     * @return
     */
	@GetMapping(value = "/index")
    public String index(Model model) {
        logger.info("--------------------打开首页！--------------------");
        model.addAttribute("userModel", super.getUserModel());
        return "index";
    }

    /**
     * GET 登录
     * @return
     */
    @GetMapping(value = "/login")
    public String login() {
        logger.info("--------------------Get请求登陆！--------------------");
        if (SecurityUtils.getSubject().isAuthenticated()) {
            return "redirect:/index";
        }
        return "login";
    }

    /**
     * 登录
     * @param request
     * @param username
     * @param password
     * @param rememberMe
     * @param captcha
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping(value = "/login")
    public Object login(HttpServletRequest request, String username, String password,
    		@RequestParam(value = "rememberMe", defaultValue = "0") Integer rememberMe, String captcha) throws Exception {
        logger.info("--------------------Post请求登陆！--------------------");
        if(StringUtil.isEmpty(username)){
            throw new ParameterException("用户名不能为空！");
        }
        if(StringUtil.isEmpty(password)){
            throw new ParameterException("密码不能为空！");
        }
        if(StringUtil.isEmpty(captcha)){
            throw new ParameterException("验证码不能为空！");
        }
        String vvcode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (!vvcode.equals(captcha)) {
            throw new ParameterException("验证码错误！");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,
                password, 1 == rememberMe, IpUtil.getMangMacIpAddr(request));
        try {
            subject.login(token);
            //记录在线用户
            ClientManager.getInstance().addClinet(request.getSession().getId(), getUserModel());
            return success();
        } catch (UnknownAccountException e) {
            throw new ParameterException("账号不存在！");
        } catch (LockedAccountException e) {
            throw new ParameterException("账户被锁定！");
        } catch (DisabledAccountException e) {
            throw new ParameterException("账号未启用！");
        } catch (IncorrectCredentialsException e) {
            throw new ParameterException("密码错误！");
        } catch (ExcessiveAttemptsException e) {
            throw new ParameterException("对不起，您的密码连续5次输入错误，锁定半小时！");
        } catch (Throwable e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 未授权
     * @return
     */
    @GetMapping(value = "/unauth")
    public String unauth() {
        if (!SecurityUtils.getSubject().isAuthenticated()) {
            return "redirect:/login";
        }
        return "unauth";
    }

    /**
     * 退出
     * @return
     */
    @GetMapping(value = "/logout")
    public String logout() {
        logger.info("登出");
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }
    
    /**
     * 强制下线
     * @param username
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/kickout")
    public Object kickOutUser(String username) {
    	ShiroCacheUtil.kickOutUser(username);
        return success();
    }
    
}
